{% extends "base.html" %}

{% block title %}购物车{% endblock %}

{% block content %}
<div class="container py-4">
    <h2 class="mb-4">购物车</h2>
    {% if cart_items %}
    <div class="card shadow-sm">
        <div class="card-body">
            <div class="table-responsive">
                <table class="table align-middle">
                    <thead>
                        <tr>
                            <th>商品</th>
                            <th>单价</th>
                            <th>数量</th>
                            <th>小计</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        {% for item in cart_items %}
                        <tr>
                            <td>{{ item.product.name }}</td>
                            <td>{{ item.product.points_required }} 积分</td>
                            <td style="width: 200px;">
                                <form action="{{ url_for('update_cart', item_id=item.id) }}" method="post" 
                                      class="d-flex align-items-center update-form"
                                      data-points-required="{{ item.product.points_required }}"
                                      data-stock="{{ item.product.stock }}">
                                    <div class="input-group input-group-sm">
                                        <button type="button" class="btn btn-outline-secondary" onclick="updateQuantity(this, -1)">-</button>
                                        <input type="number" name="quantity" value="{{ item.quantity }}" min="1" 
                                               class="form-control text-center" style="width: 60px;"
                                               onchange="checkPoints(this)">
                                        <button type="button" class="btn btn-outline-secondary" onclick="updateQuantity(this, 1)">+</button>
                                    </div>
                                </form>
                            </td>
                            <td class="points-subtotal">{{ item.product.points_required * item.quantity }} 积分</td>
                            <td>
                                <form action="{{ url_for('remove_from_cart', item_id=item.id) }}" method="post" style="display: inline;">
                                    <button type="submit" class="btn btn-sm btn-outline-danger">
                                        <i class="bi bi-trash"></i>
                                    </button>
                                </form>
                            </td>
                        </tr>
                        {% endfor %}
                    </tbody>
                    <tfoot>
                        <tr>
                            <td colspan="3" class="text-end"><strong>总计：</strong></td>
                            <td colspan="2"><strong id="total-points">{{ total_points }} 积分</strong></td>
                        </tr>
                    </tfoot>
                </table>
            </div>
            <div class="d-flex justify-content-between align-items-center mt-3">
                <a href="{{ url_for('products') }}" class="btn btn-outline-secondary">
                    <i class="bi bi-arrow-left"></i> 继续购物
                </a>
                <form action="{{ url_for('checkout') }}" method="post" style="display: inline;">
                    <button type="submit" class="btn btn-primary" id="checkout-btn"
                            {% if total_points > current_user.points %}disabled{% endif %}>
                        结算 <i class="bi bi-arrow-right"></i>
                    </button>
                </form>
            </div>
        </div>
    </div>
    {% else %}
    <div class="text-center py-5">
        <i class="bi bi-cart-x display-1 text-muted"></i>
        <h3 class="mt-3 text-muted">购物车是空的</h3>
        <a href="{{ url_for('products') }}" class="btn btn-primary mt-3">
            去购物 <i class="bi bi-arrow-right"></i>
        </a>
    </div>
    {% endif %}
</div>

<script>
function updateQuantity(button, change) {
    const form = button.closest('form');
    const input = form.querySelector('input[name="quantity"]');
    const pointsRequired = parseInt(form.dataset.pointsRequired);
    const stock = parseInt(form.dataset.stock);
    const currentPoints = {{ current_user.points }};
    
    let newValue = parseInt(input.value) + change;
    
    // 计算新的总积分
    let newTotalPoints = 0;
    document.querySelectorAll('.update-form').forEach(form => {
        const qty = form === button.closest('form') ? newValue : parseInt(form.querySelector('input').value);
        const points = parseInt(form.dataset.pointsRequired);
        newTotalPoints += qty * points;
    });
    
    // 检查积分是否足够
    if (newTotalPoints > currentPoints && change > 0) {
        // 如果积分不足且是要增加数量，则阻止增加
        return;
    }
    
    // 确保数量在合理范围内
    newValue = Math.max(1, Math.min(newValue, stock));
    input.value = newValue;
    
    // 更新小计
    const row = button.closest('tr');
    const subtotalCell = row.querySelector('.points-subtotal');
    subtotalCell.textContent = (pointsRequired * newValue) + ' 积分';
    
    // 更新总计
    updateTotalPoints();
    
    // 自动提交表单
    form.submit();
}

function updateTotalPoints() {
    let total = 0;
    document.querySelectorAll('.points-subtotal').forEach(cell => {
        total += parseInt(cell.textContent);
    });
    
    const totalElement = document.getElementById('total-points');
    totalElement.textContent = total + ' 积分';
    
    // 检查是否有足够的积分进行结算
    const checkoutBtn = document.getElementById('checkout-btn');
    const currentPoints = {{ current_user.points }};
    checkoutBtn.disabled = total > currentPoints;
    
    // 检查每个商品的增加按钮
    document.querySelectorAll('.update-form').forEach(form => {
        const pointsRequired = parseInt(form.dataset.pointsRequired);
        const quantity = parseInt(form.querySelector('input').value);
        const plusButton = form.querySelector('button[onclick*="+1"]');
        
        // 如果增加一个商品会超过用户积分，禁用增加按钮
        if ((total - (pointsRequired * quantity) + (pointsRequired * (quantity + 1))) > currentPoints) {
            plusButton.disabled = true;
            plusButton.classList.add('disabled');
        } else {
            plusButton.disabled = false;
            plusButton.classList.remove('disabled');
        }
    });
}

// 页面加载时初始化
document.addEventListener('DOMContentLoaded', function() {
    updateTotalPoints();
});
</script>

<style>
.input-group .form-control {
    text-align: center;
}

.input-group .btn {
    z-index: 0;
}

.btn-outline-danger:hover {
    transform: scale(1.1);
    transition: transform 0.2s;
}
</style>
{% endblock %} 